﻿using LogManager.Core.Models;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace LogManager.Core.Services.Location
{
    public class LogArchivingResult
    {
        public IConfiguration Configuration { get; private set; }
        public ReadOnlyCollection<LocationArchivingProgress> ArchivingProgresses { get; private set; }
        public int TotalFiles { get; private set; }
        public int TotalFilesMoved { get; private set; }
        public bool Succeeded { get; private set; }

        public LogArchivingResult(IConfiguration configuration, IList<LocationArchivingProgress> archivingProgresses)
        {
            this.Configuration = configuration;
            this.ArchivingProgresses = new ReadOnlyCollection<LocationArchivingProgress>(archivingProgresses);
            this.Succeeded = Configuration.Warehouses.All(p => HasSucceeded(p));
            var allFiles = archivingProgresses.Where(p => p.LogFilesSearchResult != null).SelectMany(p => p.LogFilesSearchResult.Files);
            this.TotalFiles = allFiles.Count();
            this.TotalFilesMoved = allFiles.Where(p => p.IsArchived).Count();
            this.Succeeded = Configuration.Warehouses.All(p => HasSucceeded(p));
        }

        public LocationArchivingProgress GetLocationResult(ILocation location)
        {
            return ArchivingProgresses.Single(p => p.Location == location);
        }

        public bool HasSucceeded(ILocation location)
        {
            var locationResult = ArchivingProgresses.Single(p => p.Location == location);

            return locationResult.SourceResult.Succeeded &&
                locationResult.DestinationResult.Succeeded && 
                locationResult.LogFilesSearchResult != null &&
                locationResult.LogFilesSearchResult.Files.All(p => p.Error == null);
        }

        public bool HasSucceeded(IServer server)
        {
            return server.Locations.All(p => HasSucceeded(p));
        }

        public bool HasSucceeded(IPlateform plateform)
        {
            return plateform.Servers.All(p => HasSucceeded(p));
        }

        public bool HasSucceeded(IWarehouse warehouse)
        {
            return warehouse.Plateforms.All(p => HasSucceeded(p));
        }
    }
}
